/*
 * Copyright (c): IT@M - Dienstleister f�r Informations- und Telekommunikationstechnik
 * der Landeshauptstadt M�nchen, 2012
 */
package de.muenchen.action;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;

import com.opensymphony.xwork2.ActionContext;

import de.muenchen.bean.RightBean;
import de.muenchen.bean.RoleBean;
import de.muenchen.bean.UserBean;
import de.muenchen.db.HibernateUtils;

/**
 * @author IT@M/A23 Matthias Karl
 * @version 1 <br/>
 *          Jun 26, 2012
 */
public class LoginAction extends BaseAction {
	
    private static final long serialVersionUID = 1L;
    
    
    private UserBean userBean;

    /**
     * Testet den Login gegen die Datenbank.
     * @return Sruts Forward
     */
	public String login(){
	    //PasswordHash für den späteren vergleich
	    String passwordHash = userBean.getSHA(userBean.getPassword());
	    //User mit eMail aus der UserBean aus DB suchen
	    UserBean dbUserBean = null;
	   
	    
        Session currentSession = HibernateUtils.getSessionFactory().getCurrentSession();
        currentSession.beginTransaction();
        List<UserBean> userList = currentSession.createQuery("from UserBean where email = '" + userBean.getEmail() + "' ").list();
        currentSession.getTransaction().commit();
        if (userList.size() != 0) {
            dbUserBean = userList.get(0);
            dbUserBean.fillRightCollection();
            dbUserBean.fillRolesCollection();
        }
        
        //Loginbedingungen testen:
        //1: eMail in Db?
        //2: IS_ACTIVE ist true
        //3: passworthash ist richtig
        if (userList.size() == 0) {
            addActionError(getText("loginAction.noEmail"));
        }else if( !dbUserBean.getIsActive()){
            addActionError(getText("loginAction.notActive"));
        } else if (passwordHash.equals(dbUserBean.getPassword())) {
            Map<String, Object> session = ActionContext.getContext().getSession();
            session.put("loginToken", dbUserBean);
            session.put("userId", dbUserBean.getUserId());
            return SUCCESS;
        }else{
            addActionError(getText("loginAction.wrongPassword"));
        }
        return INPUT;
	}
	
	public UserBean getUserBean() {
        return userBean;
    }

    public void setUserBean(UserBean userBean) {
        this.userBean = userBean;
    }


    
	
	
}
